Concurrency on the Red Planet is the art of managing multiple independent operations—such as rover navigation, life-sign telemetry, and satellite uplinks—without the system halting. In Go, an independently running task is known as a goroutine.
1. The Non-Determinism Principle
It’s best always to assume that the operations in different goroutines may run in any order. Because the Go runtime schedules tasks across available cores, we cannot rely on one rover finishing its scan before another begins its transmission without explicit synchronization.
go printGopher(c) // Launches a new independent task
2. Synchronization Mechanics
To manage these tasks, Go provides two primary tools:
- Mutual Exclusion: Goroutines can use a
mutexto exclude each other from doing something at the same time. - The Select Statement: This looks like a switch statement where each case holds a channel receive or send.
selectwaits until one case is ready and then runs it.
3. The Worker Skeleton
Long-lived workers typically utilize an infinite loop combined with select to monitor multiple communication channels simultaneously:
func worker() {
for {
select {
// Wait for channels here.
}
}
}
for {
select {
// Wait for channels here.
}
}
}
TERMINAL
bash — 80x24
> Ready. Click "Run" to execute.
>